package com.qiche.controller.mgr;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.github.pagehelper.PageInfo;
import com.qiche.aspect.Result;
import com.qiche.config.YmlConfig;
import com.qiche.constant.AccountType;
import com.qiche.dto.BankInfoDto;
import com.qiche.dto.IntroductionDto;
import com.qiche.dto.MerchantDto;
import com.qiche.enums.ResultEnum;
import com.qiche.model.*;
import com.qiche.redis.RedisService;
import com.qiche.service.*;
import com.qiche.service2.Store2Service;
import com.qiche.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 门店管理控制器
 */
@Api(value = "/merchants", description = "门店管理控制器")
@RestController
@RequestMapping("/merchants")
public class MerchantController {
    @Resource
    private MerchantService merchantService;
    @Resource
    private RegionService regionService;
    @Resource
    private UserService userService;
    @Resource
    private Store2Service store2Service;
    @Autowired
    private YmlConfig ymlConfig;
    @Autowired
    private RedisService redisService;
    @Autowired
    private BankinfoChangeLogService bankinfoChangeLogService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private SubscribeConfigService configService;
    @Autowired
    private SpecialOfferService specialOfferService;
    @Autowired
    private AgentService agentService;

    @ApiOperation(value = "根据条件和分页获取门店列表")
    @GetMapping
    public Map<String, Object> getAll(Merchant merchant, @RequestParam(required = false, defaultValue = "1") int page,
                                      @RequestParam(required = false, defaultValue = "10") int limit) throws Exception {
        Map<String, Object> map = new HashMap<>();
        User currentUser=UserUtils.getCurrentUser();
        if(currentUser.getAccountType()!=AccountType.AGENT){
            return null;
        }

        merchant.setAgentId(agentService.selectByAccountId(currentUser.getId()).getId());
        PageInfo<Merchant> pageInfo = merchantService.selectByPage(merchant, page, limit);
        // 封装区域名
        List<Region> regions = regionService.selectAll();
        Map<Long, String> regionMap = new HashMap<>();

        for (Region region : regions) {
            regionMap.put(region.getId(), region.getRegionName());
        }
        List<MerchantDto> dtos = new ArrayList<MerchantDto>();
        pageInfo.getList().forEach(mer -> {
            mer.setRegionName(regionMap.get(mer.getRegionId()));
            MerchantDto dto = new MerchantDto();
            BeanUtils.copyProperties(mer, dto);
            User user = userService.selectByMerchantId(mer.getId().intValue());
            if (user != null) {
                dto.setUsername(user.getUsername());
            }
            dtos.add(dto);
        });

        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", pageInfo.getTotal());
        map.put("data", dtos);
        return map;
    }

    @ApiOperation(value = "获取所有的门店列表")
    @GetMapping(value = "/merchants.json")
    public Result getAllMerchantList() {
        List<Merchant> merchants = null;
        User currentUser = UserUtils.getCurrentUser();
        //非管理员账户无法获取
        if (AccountType.ADMIN == currentUser.getAccountType()) {
            merchants = merchantService.selectByExample(null);
        } else {
            merchants = new ArrayList<>();
        }
        return Result.createBySuccess(merchants);
    }

    @ApiOperation(value = "获取卡券系统的所有门店列表")
    @GetMapping(value = "/piccStores.json")
    public Result getAllPiccStoreList() {
        List<Store2> store2List = store2Service.selectByExample(null);
        return Result.createBySuccess(store2List);
    }


    @ApiOperation(value = "添加门店信息")
    @PostMapping
    public Result add(@RequestBody MerchantDto dto) {
        boolean isValid = userService.isUsernameExist(dto.getUsername());
        if (isValid) {
            return Result.createByErrorMessage("用户名已经存在");
        }

        Merchant merchant = new Merchant();
        BeanUtils.copyProperties(dto, merchant);
        String lnglat = dto.getLnglat();
        if (StringUtils.isNotBlank(lnglat)) {
            merchant.setLng(Double.parseDouble(lnglat.split(",")[0]));
            merchant.setLat(Double.parseDouble(lnglat.split(",")[1]));

        }
        User currentUser = UserUtils.getCurrentUser();
        Agent agent = agentService.selectByAccountId(currentUser.getId());
        if (agent != null) {
            merchant.setAgentId(agent.getId());
        }
        Result<Merchant> result = merchantService.saveMerchant(merchant);
        if (result.isSuccess()) {
            User user = new User();
            user.setUsername(dto.getUsername());
            user.setPassword(dto.getPassword());
            user.setMerchantId(result.getData().getId().intValue());
            Result<User> registerRes = userService.register(user);

            //联动生成门店的钱包空记录 和 预约设置空记录 和特价记录
            Wallet wallet = new Wallet();
            wallet.setMerchantId(result.getData().getId().intValue());
            walletService.save(wallet);

            SubscribeConfig config = new SubscribeConfig();
            config.setMerchantId(result.getData().getId());
            configService.save(config);

            SpecialOffer offer = new SpecialOffer();
            offer.setMerchantId(result.getData().getId());
            specialOfferService.save(offer);

            if (registerRes.isSuccess()) {
                return Result.createBySuccessMessage("保存成功");
            }
            return registerRes;
        }
        return result;
    }

    @ApiOperation(value = "更新门店信息")
    @PutMapping
    public Result update(@RequestBody MerchantDto dto) {
        Merchant merchant = new Merchant();
        BeanUtils.copyProperties(dto, merchant);
        String lnglat = dto.getLnglat();
        if (StringUtils.isNotBlank(lnglat)) {
            merchant.setLng(Double.parseDouble(lnglat.split(",")[0]));
            merchant.setLat(Double.parseDouble(lnglat.split(",")[1]));

        }
        Result result = merchantService.updateMerchant(merchant);
        if (result.isSuccess()) {
            User temp = userService.selectByMerchantId(dto.getId().intValue());
            // 重置密码
            if ("on".equals(dto.getResetPass())) {
                temp.setUsername(temp.getUsername());
                temp.setPassword("123456");
                PasswordHelper helper = new PasswordHelper();
                helper.encryptPassword(temp);
                userService.updateNotNull(temp);
            }
        }
        return result;
    }

    @ApiOperation(value = "根据ID获取门店信息")
    @GetMapping(value = "/getById/{id}")
    public Result getById(@PathVariable("id") Long id) {
        Merchant bean = merchantService.selectById(id);
        if (bean == null) {
            return Result.createByErrorMessage("不存在的门店");
        }
        MerchantDto dto = new MerchantDto();
        BeanUtils.copyProperties(bean, dto);
        User user = userService.selectByMerchantId(bean.getId().intValue());
        if (user != null) {
            dto.setUsername(user.getUsername());
            dto.setPassword(user.getPassword());
            dto.setUserId(user.getId().longValue());
        }
        return Result.createBySuccess(dto);
    }

    @ApiOperation(value = "根据ID删除门店信息")
    @DeleteMapping(value = "/delete/{id}")
    public Result delete(@PathVariable("id") Long id) {
        return merchantService.delMerchant(id);
    }

    @ApiOperation(value = "上传门店LOGO图片")
    @PostMapping("/upload")
    public Result uploadLogo(MultipartFile file) {
        try {
            String paths = FastDFSUtils.uploadPic(file);
            return Result.createByResultEnum(ResultEnum.SUCCESS, ymlConfig.getFastdfsDomainUrl() + paths);
        } catch (MultipartException e) {
            e.printStackTrace();
            return Result.createByErrorMessage("上传失败,图片超过大小限制");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.createByResultEnum(ResultEnum.FAILURE);
        }
    }

    @ApiOperation(value = "获取当前登录门店的预留手机号")
    @GetMapping(value = "/getPhoneForCurrentMerchant")
    public Result getPhoneForCurrentMerchant() {
        UserUtils.getCurrentUser();
        Merchant bean = merchantService.selectById(UserUtils.getCurrentUser().getMerchantId().longValue());
        if (bean == null) {
            return Result.createByErrorMessage("不存在的门店");
        }
        return Result.createBySuccess(bean.getPhone());
    }

    @ApiOperation(value = "获取当前登录门店的钱包信息")
    @GetMapping(value = "/getWalletForCurrentMerchant")
    public Result getWalletForCurrentMerchant() {
        Wallet wallet = walletService.selectByMerchantId(UserUtils.getCurrentUser().getMerchantId().longValue());
        return Result.createBySuccess(wallet);
    }

    @ApiOperation(value = "获取当前登录门店的银行卡更换记录")
    @GetMapping(value = "/getBCLogForCurrentMerchant/{id}")
    public Result getBCLogForCurrentMerchant(@PathVariable("id") Long merchantId) {
        List<BankinfoChangeLog> logList = bankinfoChangeLogService.selectListByMerchantId(merchantId);
        return Result.createBySuccess(logList);
    }


    @ApiOperation(value = "获取当前门店是否绑定银行卡信息")
    @GetMapping(value = "/isBindBankInfo")
    public Result isBindBankInfo() {
        Merchant bean = merchantService.selectById(UserUtils.getCurrentUser().getMerchantId().longValue());
        if (bean != null) {
            if (bean.getRcvAcctName() != null && bean.getRcvBankNo() != null && bean.getRcvAcctno() != null) {
                BankInfoDto bankInfoDto = new BankInfoDto();
                bankInfoDto.setRcvBankNo(bean.getRcvBankNo());
                bankInfoDto.setRcvAcctName(bean.getRcvAcctName());
                return Result.createBySuccess(bankInfoDto);
            }
        }
        return Result.createByError();
    }

    @ApiOperation(value = "门店绑定银行卡信息")
    @PostMapping(value = "/bindBankInfo")
    public Result bindBankInfo(@RequestBody @Validated BankInfoDto bankInfoDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.createByErrorMessage(bindingResult.getFieldError().getDefaultMessage());
        }
        String verifyCode = bankInfoDto.getVerifyCode();
        Merchant bean = merchantService.selectById(UserUtils.getCurrentUser().getMerchantId().longValue());
        Object verifyCodeInRedis = redisService.get(bean.getPhone() + "bankInfoVerifyCode");

        //String verifyCodeInRedis=  redisManager.getString(bean.getPhone() + "bankInfoVerifyCode");
        if (verifyCodeInRedis == null || !verifyCode.equals(verifyCodeInRedis.toString())) {
            return Result.createByErrorMessage("验证码错误");
        }

        bean.setRcvAcctno(bankInfoDto.getRcvAcctno());
        bean.setRcvAcctName(bankInfoDto.getRcvAcctName());
        bean.setRcvBankNo(bankInfoDto.getRcvBankNo());
        int updateCount = merchantService.updateNotNull(bean);

        if (updateCount > 0) {
            //插入银行卡更改记录
            BankinfoChangeLog bankinfoChangeLog = new BankinfoChangeLog();
            bankinfoChangeLog.setMerchantId(bean.getId());
            bankinfoChangeLog.setOldCardcode(bean.getRcvBankNo());
            bankinfoChangeLog.setNewCardcode(bankInfoDto.getRcvBankNo());
            bankinfoChangeLogService.save(bankinfoChangeLog);
            return Result.createBySuccessMessage("修改成功");
        }
        return Result.createByErrorMessage("修改失败");
    }

    @ApiOperation(value = "获取绑定银行卡信息的手机验证码")
    @PostMapping(value = "/getBankInfoVerifyCode")
    public Result getBankInfoVerifyCode(String phone) throws ClientException {
        SendSmsResponse resp = null;
        String verifyCode = MathUtis.getRandomString(6);
        resp = AliyunSmsUtils.sendSms3(phone, verifyCode);
        if (StringUtils.isNotBlank(resp.getCode()) && resp.getCode().equals("OK")) {
            //redisManager.set(phone + "bankInfoVerifyCode", verifyCode, 60 * 5);
            redisService.set(phone + "bankInfoVerifyCode", verifyCode, 300L);
            return Result.createBySuccessMessage("发送成功");
        }
        return Result.createByErrorMessage("发送失败");
    }


    @ApiOperation(value = "提交门店介绍设置")
    @PostMapping(value = "/saveIntroduction")
    public Result saveIntroduction(String merchantImg, String introduction, String businessTime) {

        User user = UserUtils.getCurrentUser();
        Merchant merchant = merchantService.selectById(user.getMerchantId().longValue());
        merchant.setBusinessTime(businessTime);
        merchant.setMerchantImg(merchantImg);
        merchant.setIntroduction(introduction);
        int updateCount = merchantService.updateNotNull(merchant);
        if (updateCount > 0) {
            return Result.createBySuccessMessage("设置成功");
        }

        return Result.createByErrorMessage("设置失败");
    }


    @ApiOperation(value = "获取当前门店介绍")
    @GetMapping(value = "/getIntroduction")
    public Result getIntroduction() {
        User user = UserUtils.getCurrentUser();
        Merchant merchant = merchantService.selectById(user.getMerchantId().longValue());
        IntroductionDto dto = new IntroductionDto();
        dto.setBusinessTime(merchant.getBusinessTime());
        dto.setIntroduction(merchant.getIntroduction());
        dto.setMerchantImg(merchant.getMerchantImg());
        return Result.createBySuccess(dto);
    }

    @ApiOperation(value = "根据ID获取门店介绍")
    @GetMapping(value = "/getIntroduction/{merchantId}")
    public Result getIntroductionByMerchantId(@PathVariable("merchantId") Long merchantId) {
        Merchant merchant = merchantService.selectById(merchantId);
        if (merchant == null) {
            return Result.createByErrorMessage("不存在的门店");
        }
        IntroductionDto dto = new IntroductionDto();
        dto.setIntroduction(merchant.getIntroduction());
        dto.setLat(merchant.getLat());
        dto.setLng(merchant.getLng());
        dto.setAddress(merchant.getAddress());
        dto.setBusinessTime(merchant.getBusinessTime());
        dto.setLandline(merchant.getLandline());
        dto.setMerchantImg(merchant.getMerchantImg());
        dto.setMerchantName(merchant.getName());
        return Result.createBySuccess(dto);
    }

    @ApiOperation(value = "根据ID获取门店绑定的公众号名称")
    @GetMapping(value = "/getOfficialName")
    public Result getOfficialName() {
        User user = UserUtils.getCurrentUser();
        Merchant merchant = merchantService.selectById(user.getMerchantId().longValue());
        return Result.createBySuccess(merchant.getOfficialName());
    }



    @ApiOperation(value = "根据条件获取当前门店列表")
    @GetMapping(value = "/getAllMerchantsByCondition")
    public Result getAllMerchantsByCondition(String name) {
        User currentUser = UserUtils.getCurrentUser();
        Agent agent=agentService.selectByAccountId(currentUser.getId());
        if(agent== null){
            return null;
        }
        Example example =new Example(Merchant.class);
        Example.Criteria criteria=example.createCriteria();
        if(StringUtils.isNotBlank(name)){
            criteria.andLike("name","%"+name+"%");
        }
        criteria.andEqualTo("agentId", agent.getId());
        List<Merchant> merchantList= merchantService.selectByExample(example);
        return Result.createBySuccess(merchantList);
    }

}
